package com.example.malldemo.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JwtToken生成的工具类
 * token的格式： header头部+payload负载+signature签名
 * 验证流程：
 *  1. 在头部信息中声明算法和常量，然后把header使用json转化为字符串
 *  2. 在载荷中声明用户信息，同时还有一些其他的内容
 *  3. 使用header中声明的加密算法和每个项目随机生成的secret来进行加密
 *  4. 解密的时候服务端可以直接使用secret进行解密
 *
 *  header格式:{"alg":"HS512","typ":"JWT"}
 *  payload格式(用户名、创建时间、过期时间)
 *  {"sum":"wang","created":1489079981393,"exp":1489684781}
 *  signature的生成算法
 *  HMACSHA512(base64UrlEncode(header)+"."+base64UrlEncode(payload),secret)
 */

@Component
public class JwtTokenUtil {
    public static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

    public static final String CLAIN_KEY_USERNAME = "sub";

    public static final String CLAIN_KEY_CREATED = "created";

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+expiration*1000))
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            LOGGER.info("JWT格式验证失败{}", token);
        }
        return claims;
    }

    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && isTokenExpired(token);
    }

    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return !expiredDate.before(new Date());
    }

    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIN_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIN_KEY_CREATED, new Date());
        return generateToken(claims);
    }
    public boolean canRefresh(String token) {
        return isTokenExpired(token);
    }

    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIN_KEY_CREATED, new Date());
        return generateToken(claims);
    }
}
